package cn.com.fssg.platform.base.handler.impl.cl.jiesuan;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import cn.com.fssg.platform.biz.ExtendUtil;
import cn.com.fssg.platform.modules.system.entity.SysUser;
import cn.hutool.crypto.SmUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @className: ClDisabledCtl
 * @description: TODO 类描述
 * @author: xzm
 * @date: 2025/10/20
 **/
@Component
public class ClDisabledCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
    //@Autowired
    //private NamedParameterJdbcTemplate jdbcTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String type = jsonObject.getString("type");
        //id查询
        if(StringUtils.equals(type, "0")){
            //查询
            String id = jsonObject.getString("id");
            String querySql = "select * from pxone.su_user where id =:id";
            Map<String,Object> map = new HashMap<>();
            map.put("id",id);
            Map<String,Object> queryMap = jdbcTemplate.queryForMap(querySql, map);
            return queryMap;
        } else if(StringUtils.equals(type, "1")){
            //添加用户
            //判断账号是否存在
            String loginname = jsonObject.getString("loginname");
            String querySql = "select count(id) from pxone.su_user where loginname =:loginname";
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("loginname",loginname);
            Map<String,Object> queryUserMap = jdbcTemplate.queryForMap(querySql, queryMap);
            if(StringUtils.equals(queryUserMap.get("count").toString(), "1")){
                return new Exception("添加的账号已存在");
            }
            String roleSql = "select * from pxone.su_role where role_code =:role_code";
            Map<String,Object> queryRoleMap = new HashMap<>();
            queryRoleMap.put("role_code",jsonObject.getString("role_code"));
            Map<String,Object> queryRole = jdbcTemplate.queryForMap(roleSql, queryRoleMap);
            //添加
            JSONObject json = new JSONObject();
            String id = BizUtil.cur().getSnowflakeIdStr();
            //String id = "123333333311133";
            json.put("id",id);
            String password = jsonObject.getString("password");
            String salt = jsonObject.getString("salt");
            json.put("realname", jsonObject.getString("realname"));
            //String pwd = SmUtil.sm3(loginname +":"+ password);
            json.put("loginname", loginname);
            json.put("password", password);
            json.put("salt", salt);
            json.put("sex", jsonObject.getLong("sex"));
            json.put("status", jsonObject.getLong("status"));
            json.put("updateBy", BizUtil.cur().curUserId());
            json.put("createBy", BizUtil.cur().curUserId());
            json.put("updateTime", new Date());
            json.put("createTime", new Date());
            json.put("del_flag", 0);
            json.put("user_identity", 1);
            json.put("create_time", new Date());
            json.put("selectedroles",queryRole.get("id"));
            json.put("tecjrlhh","tecjrlhh");
            ExtendUtil.cur().addUser(json);
            return insetCjr(json);
        }else if(StringUtils.equals(type, "2")){
            //修改用户信息(除密码外)
            String id = jsonObject.getString("id");
            SysUser user = new SysUser();
            user.setId(id);
            user.setUpdateBy(BizUtil.cur().curUserId());
            user.setUpdateTime(new Date());
            user.setLastModifyPasswordTime(new Date());
            user.setRealname(jsonObject.getString("realname"));
            user.setSex(jsonObject.getInteger("sex"));
            user.setStatus(jsonObject.getInteger("status"));
            return ExtendUtil.cur().updateUserInfo(user);
        }else if(StringUtils.equals(type, "3")){
            //删除
            String batch = jsonObject.getString("batch");
            SysUser user = new SysUser();
            //单次删除
            if(StringUtils.equals(batch, "Y")){
                String id = jsonObject.getString("id");
                user.setId(id);
                user.setDelFlag(1);
                boolean con = ExtendUtil.cur().updateUserInfo(user);
                deleteCjr(id);
                return  con;
            }
            //批量删除
            if(StringUtils.equals(batch, "N")){
                jsonObject.getJSONArray("id").forEach(item->{
                    user.setId(item.toString());
                    user.setDelFlag(1);
                    ExtendUtil.cur().updateUserInfo(user);
                    deleteCjr(item.toString());
                });
            }
            return batch;

        }else if(StringUtils.equals(type, "4")){
            //修改密码
            String loginname = jsonObject.getString("loginname");
            String id = jsonObject.getString("id");
            SysUser user = new SysUser();
            user.setId(id);
            user.setLoginname(loginname);
            String password  = jsonObject.getString("password");
            if(StringUtils.isNotBlank(loginname)){
                boolean flag = ExtendUtil.cur().changePassword(loginname,password);
                return flag;
            }
            return null;
        }else if(StringUtils.equals(type, "5")){
            //修改残疾人信息------康复残疾人信息档案
            String id = jsonObject.getString("id");
            //判断cl_canjiren表中是否存在记录
            String querySql = "select count(id) from cl_canjiren where id =:id";
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("id",id);
            Map<String,Object> queryUserMap = jdbcTemplate.queryForMap(querySql, queryMap);
            if(StringUtils.equals(queryUserMap.get("count").toString(), "0")){
                //没有，做添加操作
                insetCJR(jsonObject);
            }else{
                //有 做修改操作
                upCjr(jsonObject);
            }
            //同步user表
            SysUser user = new SysUser();
            user.setId(jsonObject.getString("id"));
            user.setRealname(jsonObject.getString("cjr_name"));
            if(StringUtils.equals(jsonObject.getString("cjr_sex"), "0")){
                //男
                user.setSex(1);
            }else if(StringUtils.equals(jsonObject.getString("sex"), "1")){
                //女
                user.setSex(2);
            }
            boolean flag = ExtendUtil.cur().updateUserInfo(user);
            return flag;
        }else if(StringUtils.equals(type, "6")){
            //修改残疾人信息------康复残疾人信息档案
            String id = jsonObject.getString("id");
            //判断cl_canjiren表中是否存在记录
            String querySql = "select count(id) from cl_canjiren where id =:id";
            Map<String,Object> map = new HashMap<>();
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("id",id);
            Map<String,Object> queryUserMap = jdbcTemplate.queryForMap(querySql, queryMap);
            if(StringUtils.equals(queryUserMap.get("count").toString(), "0")){
                //没有，做添加操作
                String userSql = "select * from pxone.su_user where id =:id";
                map = jdbcTemplate.queryForMap(userSql, queryMap);
                Optional<Object> valueSex = Optional.ofNullable(map.get("sex"));
                if(valueSex.isPresent()){
                    if(StringUtils.equals(map.get("sex").toString(), "1")){
                        //男
                        map.put("cjr_sex", "0");
                    }else if(StringUtils.equals(map.get("sex").toString(), "2")){
                        //女
                        map.put("cjr_sex", "1");
                    }
                }
                Optional<Object> valueReal = Optional.ofNullable(map.get("realname"));
                if(valueReal.isPresent()){
                    map.put("cjr_name", map.get("realname"));
                }else{
                    Optional<Object> valueLogin = Optional.ofNullable(map.get("loginname"));
                    if(valueLogin.isPresent()) {
                        map.put("cjr_name", map.get("loginname"));
                    }else{
                        map.put("cjr_name", "");
                    }
                }
                return map;
            }else{
                //有 做修改操作
                String userSql = "select * from pxone.su_user where id =:id";
                map = jdbcTemplate.queryForMap(userSql, queryMap);
                return map;
            }
        }
        return null;
    }

    /** 添加cl_canjiren */
    public int insetCjr(JSONObject json) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",json.getString("id"));
        map.put("cjr_name", json.getString("realname"));
        if(StringUtils.equals(json.getString("sex"), "1")){
            //男
            map.put("cjr_sex", "0");
        }else if(StringUtils.equals(json.getString("sex"), "2")){
            //女
            map.put("cjr_sex", "1");
        }
        map.put("del_flag", "0");
        map.put("create_by",json.getString("createBy"));
        map.put("create_time",json.get("create_time"));
        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> field = new ArrayList<>();
        StringBuffer sqlFields = new StringBuffer();
        sqlFields.append("INSERT INTO cl_canjiren (");
        map.forEach((k, v) -> {
            if (v != null) {
                field.add(":"+k);
                fields.add(k);
            }
        });
        sqlFields.append(String.join(", ", fields)).append(") VALUES (").append(String.join(",",field)).append(")");
        return jdbcTemplate.update(sqlFields.toString(), map);
    }

    /** 菜单 残疾人账号管理 同步cl_canjiren信息 */
    public int insetCJR(JSONObject json) {
        StringBuffer sql = new StringBuffer();
        Map<String,Object> map = new HashMap<>();
        map.put("id",json.getString("id"));
        map.put("cjr_name",json.getString("cjr_name"));
        map.put("cjr_sex",json.getString("cjr_sex"));
        map.put("cjr_birthday",json.getString("cjr_birthday"));
        map.put("cjr_minzu",json.getString("cjr_minzu"));
        map.put("cjr_hukou",json.getString("cjr_hukou"));
        map.put("cjr_idcard",json.getString("cjr_idcard"));
        map.put("school",json.getString("school"));
        map.put("has_cjr_card",json.getString("has_cjr_card"));
        map.put("cjr_num",json.getString("cjr_num"));
        map.put("cjr_type",json.getString("cjr_type"));
        map.put("cjr_cj_level",json.getString("cjr_cj_level"));
        map.put("cjr_bx",json.getString("cjr_bx"));
        map.put("cjr_jjqk",json.getString("cjr_jjqk"));
        map.put("cjr_address",json.getString("cjr_address"));
        map.put("cjr_jhr",json.getString("cjr_jhr"));
        map.put("jhr_idcard",json.getString("jhr_idcard"));
        map.put("cjr_jhr_gx",json.getString("cjr_jhr_gx"));
        map.put("cjr_jhr_phone",json.getString("cjr_jhr_phone"));
        map.put("create_by", BizUtil.cur().curUserId());
        map.put("create_time",new Date());
        map.put("update_by", BizUtil.cur().curUserId());
        map.put("update_time",new Date());
        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> field = new ArrayList<>();
        StringBuffer sqlFields = new StringBuffer();
        sqlFields.append("INSERT INTO cl_canjiren (");
        map.forEach((k, v) -> {
            if (v != null) {
                field.add(":"+k);
                fields.add(k);
            }
        });
        sqlFields.append(String.join(", ", fields)).append(") VALUES (").append(String.join(",",field)).append(")");
        return jdbcTemplate.update(sqlFields.toString(), map);
    }



    /** 软删除cl_canjiren */
    public int deleteCjr(String id) {
        StringBuffer sql = new StringBuffer();
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("del_flag","1");
        sql.append("UPDATE cl_canjiren SET del_flag=:del_flag WHERE id=:id");
        //封装新增的sql语句
        return jdbcTemplate.update(sql.toString(), map);
    }

    /** 菜单 残疾人账号管理 同步cl_canjiren信息 */
    public int upCjr(SysUser user) {
        StringBuffer sql = new StringBuffer();
        Map<String,Object> map = new HashMap<>();
        map.put("id",user.getId());
        map.put("cjr_name",user.getRealname());
        map.put("cjr_sex",user.getSex());
        sql.append("UPDATE cl_canjiren SET cjr_name=:cjr_name,cjr_sex=:cjr_sex WHERE id=:id");
        //封装新增的sql语句
        return jdbcTemplate.update(sql.toString(), map);
    }

    /** 菜单 残疾人账号管理 同步cl_canjiren信息 */
    public int upCjr(JSONObject json) {
        StringBuffer sql = new StringBuffer();
        Map<String,Object> map = new HashMap<>();
        map.put("id",json.getString("id"));
        map.put("cjr_name",json.getString("cjr_name"));
        map.put("cjr_sex",json.getString("cjr_sex"));
        map.put("cjr_birthday",json.getString("cjr_birthday"));
        map.put("cjr_minzu",json.getString("cjr_minzu"));
        map.put("cjr_hukou",json.getString("cjr_hukou"));
        map.put("cjr_idcard",json.getString("cjr_idcard"));
        map.put("school",json.getString("school"));
        map.put("has_cjr_card",json.getString("has_cjr_card"));
        map.put("cjr_num",json.getString("cjr_num"));
        map.put("cjr_type",json.getString("cjr_type"));
        map.put("cjr_cj_level",json.getString("cjr_cj_level"));
        map.put("cjr_bx",json.getString("cjr_bx"));
        map.put("cjr_jjqk",json.getString("cjr_jjqk"));
        map.put("cjr_address",json.getString("cjr_address"));
        map.put("cjr_jhr",json.getString("cjr_jhr"));
        map.put("jhr_idcard",json.getString("jhr_idcard"));
        map.put("cjr_jhr_gx",json.getString("cjr_jhr_gx"));
        map.put("cjr_jhr_phone",json.getString("cjr_jhr_phone"));
        map.put("update_by", BizUtil.cur().curUserId());
        map.put("update_time",new Date());

        sql.append("UPDATE cl_canjiren SET ");
        sql.append("cjr_name=:cjr_name,cjr_sex=:cjr_sex,cjr_birthday=:cjr_birthday,cjr_minzu=:cjr_minzu,");
        sql.append("cjr_hukou=:cjr_hukou,cjr_idcard=:cjr_idcard,school=:school,has_cjr_card=:has_cjr_card,cjr_num=:cjr_num,cjr_type=:cjr_type,");
        sql.append("cjr_cj_level=:cjr_cj_level,cjr_bx=:cjr_bx,cjr_jjqk=:cjr_jjqk,cjr_address=:cjr_address,cjr_jhr=:cjr_jhr,jhr_idcard=:jhr_idcard,");
        sql.append("cjr_jhr_gx=:cjr_jhr_gx,cjr_jhr_phone=:cjr_jhr_phone,update_by=:update_by,update_time=:update_time ");
        sql.append("WHERE id=:id");
        //封装新增的sql语句
        return jdbcTemplate.update(sql.toString(), map);
    }




}
